package com.example.wiki.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.wiki.entity.Content;
import com.example.wiki.entity.Doc;
import com.example.wiki.entity.req.DocQueryReq;
import com.example.wiki.entity.req.DocSaveReq;
import com.example.wiki.entity.resp.DocQueryResp;
import com.example.wiki.entity.resp.PageResp;
import com.example.wiki.exception.BusinessException;
import com.example.wiki.exception.BusinessExceptionCode;
import com.example.wiki.mapper.DocMapper;
import com.example.wiki.service.IContentService;
import com.example.wiki.service.IDocService;
import com.example.wiki.util.CopyUtil;
import com.example.wiki.util.RedisUtil;
import com.example.wiki.util.RequestContext;
import com.example.wiki.websocket.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 文档表 服务实现类
 * </p>
 *
 * @author jerry
 * @since 2024-10-08
 */
@Service
public class DocServiceImpl extends ServiceImpl<DocMapper, Doc> implements IDocService {

    //打印日志
    private static final Logger LOG = LoggerFactory.getLogger(IDocService.class);

    @Autowired
    IContentService contentService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private WebSocketServer webSocketServer;

    @Override
    public String findContent(Long id) {
        //根据id查询content
        Content content = contentService.getById(id);
        if (content != null) {
            return content.getContent();//返回content的字符串
        }
        return null;
    }

    //新增doc和修改doc
    @Override
    @Transactional
    public boolean saveOrUpdateDoc(DocSaveReq req) {
        //1、修改或者新增Doc对象
        Doc doc = CopyUtil.copy(req, Doc.class);
        boolean save1 = this.saveOrUpdate(doc);
        //2、修改或者新增Content对象[拷贝content的富文本内容]
        Content content = CopyUtil.copy(req, Content.class);
        content.setId(doc.getId());//从表的id是关联主表
        boolean save2 = contentService.saveOrUpdate(content);
        //返回结果
        return save1 && save2;
    }

    @Override
    public PageResp<DocQueryReq> getDocListByPage(DocQueryReq req) {
        Page<Doc> page = new Page<>(req.getPage(), req.getSize());
        page = this.page(page);
        List<Doc> list = page.getRecords();

        LOG.info("总行数：{}", page.getTotal() + "");
        LOG.info("总页数：{}", page.getPages() + "");

        List<DocQueryReq> docResps = CopyUtil.copyList(list, DocQueryReq.class);

        PageResp<DocQueryReq> repsPage = new PageResp<>();
        repsPage.setList(docResps);
        repsPage.setTotal(page.getTotal());
        return repsPage;
    }


    @Override
    public List<DocQueryResp> allList(DocQueryReq req) {
        QueryWrapper<Doc> wrapper = new QueryWrapper<>();
        //根据ebookid查询文档列表
        wrapper.eq(req.getEbookId() != null && req.getEbookId() != 0, "ebook_id", req.getEbookId());
        wrapper.orderByAsc("sort");
        List<Doc> list = this.list(wrapper);

        List<DocQueryResp> resp = CopyUtil.copyList(list, DocQueryResp.class);
        return resp;
    }

    @Override
    public int increaseViewCount(int id) {
        return this.baseMapper.increaseViewCount(id);
    }


    @Override
    public int increaseVoteCount(int id) {
        String ip = RequestContext.getRemoteAddr();
        //推送消息
        Doc docDB = this.baseMapper.selectById(id);

        if (redisUtil.validateRepeat("DOC_VOTE"+id+"_",+10)){
            webSocketServer.sendInfo("【"+docDB.getName()+"】被点赞了！");
            return this.baseMapper.increaseVoteCount(id);
        } else {
            webSocketServer.sendInfo("【"+docDB.getName()+"】已经点过赞了！");
            throw new BusinessException(BusinessExceptionCode.VOTE_REPEAT);
        }

    }

    @Override
    public int updateEbookInfo() {
        return this.baseMapper.updateEbookInfo();
    }


}
